#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
from lxml import etree
import Mail
from datetime import date,datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from fake_useragent import UserAgent
import time  # 引入time模块
import Robot

#
app_id="cli_9fb6cc15aef1500e"#机器人的app_id   在飞书后台 凭证和基础信息里面获取
app_secret="uXDiQfTCP1Mdf7HirSoVodU2oZJyeuoH"#机器人的app_secret 在飞书后台 凭证和基础信息里面获取
chat_name="Hello"#发送到飞书的群组名


def getMessageContent(title,url):#获取每条预警的信息
	responce = requests.get(url, headers = {"User-Agent": UserAgent().random},timeout = 5)
	selector = etree.HTML(responce.text)
	# print responce.text se-knowledge
	content =  selector.xpath("//div[@id ='se-knowledge']/p")
	temcontent = ""
	for i in content:
		temcontent = temcontent+ i.xpath("string(.)")+"\n"
		
	temcontent = temcontent.encode('utf-8')
	temcontent = temcontent.replace("阿里云","")
	
	b = Mail.sendEmail(Mail.my_user,title,temcontent)#发送邮件
	if b:
		print("send success")
	else:
		print("send faild")
	

	fei=Robot.FeishuApi(app_id,app_secret,chat_name)
	res=fei.send_msg(temcontent)




def getMainData(url):#获取目标网址里面的每条预警公告的信息
	responce = requests.get(url, headers = {"User-Agent": UserAgent().random},timeout = 5)
	selector = etree.HTML(responce.text)
	messages = selector.xpath("//li[@class ='y-clear']")
	
	for message in (messages):
		title = message.xpath("a")
		day = message.xpath("span[@class='y-right']/text()")
		hour =  message.xpath("span/span[@class='time']/text()")

		href = title[0].get("href")
		title = title[0].xpath("string(.)")


		temp = "".join(day)+" "+"".join(hour)

		time_stamp_1 = time.strptime(temp,"%Y-%m-%d %H:%M:%S")

		timeStamp = int(time.mktime(time_stamp_1))

		global startTime 

		if timeStamp>startTime:#判断每条预警公告的时间戳大于启动的时间戳就是新的公告
			print "new  notice======================coming"
			url = "https://help.aliyun.com"+href
			getMessageContent(title,url)

		
		
		
		



if __name__ == '__main__':

	url = "https://help.aliyun.com/noticelist/9213612.html?spm=a2c4g.11174386.n2.2.40be1051mYX59f"
	global startTime
	startTime = time.time()#记录下启动时间戳
	# # getMainData(url)

	sched = BlockingScheduler()
	def my_job(text):
		print "getMainData"
		getMainData(url)
		
	print("Start collect data at 8:00am 16:00pm 24:00PM  every Day ")
	# 每天8点，16,24点。爬取下有没有新的漏洞预警
	sched.add_job(my_job, 'cron', day = "*", hour = "7,15,23",minute = "0",second = "0", args=['text'])
	sched.start()
	
	




